import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElIcon,
  ElSpace,
  ElLink,
  ElMessageBox,
  ElMessage,
  ElSelect,
  ElOption
} from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import OptionsModal from './options'
import AliIcon from '~/components/AliIocn'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'

export default defineComponent(function Advice() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const dictState = useVuexGetters('dict', ['tenantSeleceOpt'])
  const formValues = reactive<FormValuesType>({})
  const state = reactive({
    type: 'read',
    record: {},
    list: [],
    selecteds: [],
    modalVisible: false
  })
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '字典编号',
      prop: 'code',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '字典名称',
      prop: 'dictValue',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '字典值',
      prop: 'dictKey',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '字典排序',
      prop: 'sort',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '更新日期',
      prop: 'updateTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 260,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          {row.parentId !== '0' && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('updata', row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 编辑
            </ElLink>
          )}
          {row.parentId !== '0' && (
            <ElLink type="primary" onClick={() => handleOpenPushConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp; 删除
            </ElLink>
          )}
          {row.parentId === '0' && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('add', row)}>
              <ElIcon>
                <Plus />
              </ElIcon>
              &nbsp; 新增子项
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]
  //  列表数据
  const index = async () => {
    try {
      const { data } = await store.dispatch('dict/TenantDictListGet', formValues)
      state.list = data
    } catch (error) {}
  }
  //  按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  //  清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  // 打开新增、编辑
  const handleChangeOptionsModal = (type: string, record?: any) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) index()
  }
  // 打开删除消息确认框
  const handleOpenPushConfirm = (record?: any) => {
    if (!record && !state.selecteds.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    const params = record?.id || state.selecteds.map?.((item: any) => item.id)?.join(',')
    ElMessageBox.confirm('确定将选择数据删除?', '确认提示', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('dict/TenantDictRemovePost', { ids: params }).then((res) => {
          if (res?.code === 200) {
            index()
            ElMessage({ type: 'success', message: '操作成功' })
          }
        })
      })
      .catch(() => {})
  }

  onMounted(async () => {
    index()
    //  所属租户
    await store.dispatch('dict/TenantSelectGet')
  })

  return () => (
    <ElCard>
      <ProSaasTable
        tableId="DictTable"
        ref={proSaasTableRef}
        columns={columns}
        data={state.list}
        searchFormProps={{
          model: formValues
        }}
        rowKey="id"
        treeProps={{
          children: 'children'
        }}
        // headerTitle={
        //   <>
        //     <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
        //       <ElIcon>
        //         <Plus />
        //       </ElIcon>
        //       &nbsp; 新增
        //     </ElButton>
        //   </>
        // }
        searchformResponsiveCol={[
          <ElFormItem key="code" prop="code" label="">
            <ElInput
              v-model={formValues.code}
              placeholder="字典编号"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="dictValue" prop="dictValue" label="">
            <ElInput
              v-model={formValues.dictValue}
              placeholder="字典名称"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="remark" prop="remark" label="">
            <ElInput
              v-model={formValues.remark}
              placeholder="字典备注"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>,
          <ElFormItem key="tenantId" prop="tenantId">
            <ElSelect
              v-model={formValues.tenantId}
              placeholder="所属租户"
              clearable
              onChange={clearSearchTable}
            >
              {dictState.tenantSeleceOpt?.value?.map((item: any) => (
                <ElOption key={item?.tenantId} label={item?.tenantName} value={item?.tenantId!} />
              ))}
            </ElSelect>
          </ElFormItem>
        ]}
      />
      {state.modalVisible && (
        <OptionsModal
          visible={state.modalVisible}
          type={state.type}
          record={state.record}
          onCancel={() => handleChangeOptionsModal('read')}
        />
      )}
    </ElCard>
  )
})
